<%@ page import="com.google.appengine.api.blobstore.BlobstoreServiceFactory" %>
<%@ page import="com.google.appengine.api.blobstore.BlobstoreService" %>
<%@ page import="com.google.appengine.api.users.User" %>
<%@ page import="com.google.appengine.api.users.UserService" %>
<%@ page import="com.google.appengine.api.users.UserServiceFactory" %>
<%@ page import="com.google.appengine.api.datastore.DatastoreService" %>
<%@ page import="com.google.appengine.api.datastore.DatastoreServiceFactory" %>
<%@ page import="com.google.appengine.api.datastore.Entity" %>
<%@ page import="com.MediaVaultTest.UserStore" %>
<%@ page import="com.MediaVaultTest.Media" %>
<%@ page import="com.google.appengine.api.datastore.Key" %>
<%@ page import="com.google.appengine.api.datastore.KeyFactory" %>
<%@ page import="com.google.appengine.api.datastore.PreparedQuery" %>
<%@ page import="com.google.appengine.api.datastore.Query" %>
<%@ page import="javax.jdo.JDOHelper" %>
<%@ page import="javax.jdo.PersistenceManager" %>
<%@ page import="javax.jdo.PersistenceManagerFactory" %>
<%@ page import="com.MediaVaultTest.PMF" %>
<%@ page import="javax.jdo.JDOObjectNotFoundException" %>
<%@ page import="java.util.LinkedList" %>
<%@ page import="com.MediaVaultTest.Format" %>
<%@ page import="com.MediaVaultTest.Sort" %>
<%@ page import="com.MediaVaultTest.QuotaLogic" %>
<%@ page import="com.MediaVaultTest.GetAdds" %>

<%
    BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	GetAdds getAdds = new GetAdds();

%>

<!DOCTYPE HTML>
<html>

<head>
  <title>QUT Media Vault</title>
  <meta name="description" content="website description" />
  <meta name="keywords" content="website keywords, website keywords" />
  <meta http-equiv="content-type" content="text/html; charset=windows-1252" />
  <link rel="stylesheet" type="text/css" href="style/style.css" />
  <script type="text/javascript" src="http://www.google.com/jsapi"></script>
  <script type="text/javascript">
    google.load("jquery", "1.4");
  </script>
  <script type="text/javascript" src="/static/plupload/gears_init.js"></script>
  <script type="text/javascript" src="/static/plupload/plupload.full.min.js"></script>
  <script type="text/javascript" src="/static/plupload/jquery.plupload.queue.min.js"></script>
  <script type="text/javascript">
  $(function() {
      uploader = $("#uploader").pluploadQueue({
        runtimes: 'flash,html5,gears,html4',
                                use_query_string: false,
                                multipart: true,
                                flash_swf_url: '/static/plupload/plupload.flash.swf',
                                filters: [{title:'dmgs', extensions:'dmg'}],
      }).pluploadQueue();
      uploader.bind('UploadFile', function(up, file) {
        $.ajax({
            url: '/genUploadURL',
            async: false,
            success: function(data) {
              up.settings.url = data;
            },
        });
      });
    });
  </script>
</head>

<body>
  <%
  	//Setup user service and data store
	 UserService userService = UserServiceFactory.getUserService();
	 User user = userService.getCurrentUser();
	 
	 //If user logged in
	 if (user != null) {
		 DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		 PersistenceManager pm = PMF.get().getPersistenceManager();
		 
		 //Check if user system
		 String email =  user.getEmail();
		 
		 UserStore userStore = null;
		 Key key = KeyFactory.createKey(UserStore.class.getSimpleName(), email);
		 try { 
			 userStore = pm.getObjectById(UserStore.class, key);
			 //See if anything is returned\
		 } catch (JDOObjectNotFoundException e) {
			 userStore = null;
		 }
		 
		
		 //if not create them
		 if(userStore==null){
			 int up = 0;
			 int down = 0;
			 int store = 0;
			 userStore = new UserStore(email, up, down, store);
			 //userStore = new UserStore();
			 userStore.setKey(key);
			 try {
				 pm.makePersistent(userStore);
			 } finally {
				 
			 }
		} else {
			
		}
	
  %>
  <div id="main">
    <div id="header">
      <div id="logo">
        <div id="logo_text">
          <!-- class="logo_colour", allows you to change the colour of the text -->
          <h1><a href="index.jsp">Media Vault<span class="logo_colour">QUT</span></a></h1>
          <h2>Media Centre. Currently in Alpha</h2>
        </div>
        <div id="ads_top">
        	<%=
	        	getAdds.getTopBanner()
	        %>
        </div>
      </div>
      <div id="menubar">
        <ul id="menu">
          <!-- put class="selected" in the li tag for the selected page - to highlight which page you're on -->
          <li class="selected"><a href="/">General</a></li>
		  <li><a href="photos.jsp">Photos</a></li>
          <li><a href="music.jsp">Music</a></li>
          <li><a href="movies.jsp">Movies</a></li>
          <li><a href="tv_shows.jsp">TV Shows</a></li>
          <%if (userService.isUserAdmin()) {%>
          
		  <li><a href="adminPanel.jsp">Admin Panel</a></li>
		  <%} %>
         
		  <li><a href="userPanel.jsp">User Panel</a></li>
		  <li><a href="<%= userService.createLogoutURL(request.getRequestURI()) %>">Sign Out</a></li>
        </ul>
      </div>
    </div>
    <div id="site_content">
    <div class="left_sidebar">
    <h1>Quota Remaining</h1>
    <table>
    <% QuotaLogic quotaLogic = new QuotaLogic(); %>
    <tr><td>Upload</td><td><%= quotaLogic.getMBUploadRemaining(userStore) %>MB</td></tr>
    <tr><td>Download</td><td><%= quotaLogic.getMBDownloadRemaining(userStore) %>MB</td></tr>
    <tr><td>Storage</td><td><%= quotaLogic.getMBStoreRemaining(userStore) %>MB</td></tr>
    </table>
	    </div>
      <div class="sidebar">
      <h1>Search</h1>
      <form method="post" action="#">
        <p>
          <input class="search" type="text" name="search_field" value="" />
          <input name="search" type="image" style="border: 0; margin: 0 0 -5px 0;" src="style/search.png" alt="Search" title="Search" />
          <select name="Field">
          <option>Title</option>
        </select>
        </p>
      </form>
        <div id="ads_left">
	        <%=
	        	getAdds.getRightBanner()
	        %>
        </div>
        
      </div>
      <div id="content">
        <h3>Upload Files</h3>
			<form action="<%= blobstoreService.createUploadUrl("/upload") %>" method="post" enctype="multipart/form-data">
		            <input type="text" name="foo">
		            <input type="file" name="myFile"><br>
		            <input type="submit" value="Submit">
		        </form>
                <div id="uploader">
                </div>  
		        <%
		        if(request.getParameter("msg")!=null){
		        %>
		        <h3>
		        <%= request.getParameter("msg") %>
		        </h3>
		        <% } %>
		        <br>
        
		        <h3>Files in System</h3>
		        <form action="/multiDelete" method="post"><table width="540px"><tr>
		        <%
		        String field = request.getParameter("field");
		        String order = request.getParameter("ord");
		        String newOrder = "asc";
		        if(field==null||order==null){
		        	field="";
		        	order="";
		        }
		        if(order.equals("asc")){
		        	newOrder = "dsc";
		        } else if(order.equals("dsc")){
		        	newOrder = "asc";
		        }
		        LinkedList<String> menu = new LinkedList<String>();
		        menu.add("Title");
		        menu.add("Size");
		        for(int i = 0; i < menu.size(); i++){
		        	if(field.equals(menu.get(i))){
			        	%>
			        	<td><a href="/index.jsp?field=<%=menu.get(i)%>&ord=<%= newOrder %>"><%=menu.get(i)%><img src="style/<%= order %>.png" width="16px" height"16px" /></a></td>
			        	<%
			        } else {
			        	%>
			        	<td><a href="/index.jsp?field=<%=menu.get(i)%>&ord=asc"><%=menu.get(i)%></a></td>
			        	<%
			        }
		        }
		       %>
		        <td>Download</td><td>Stream</td><td>Delete</td></tr>
		        <%
		        //We have no files for current user
		        LinkedList<Media> tempList = userStore.getMedia();
		        Sort sort = new Sort(tempList);
		        String value = request.getParameter("search_field");
		        String onField = request.getParameter("Field");
		        if(value!=null&&onField!=null){
		        	%> <h2> Searching by <%= onField %> </h2> <%
		        	tempList = sort.search(onField, value);
		        }
		        if(field!=""&&order!=""){
		        	
		        	tempList = sort.sortBy(field, order);
		        }
		        int numMediaFiles = tempList.size();
		        if (numMediaFiles==0){
		        	%> <h2>No files found for current user</h2> <%
		        } else {
		        	//Display all files for user
			        int current = 0;
			        while(current < numMediaFiles) { 
			        	Media media = tempList.get(current);
			        	Format format = media.getFirstFormat(); %>
			        	<tr>
			        	<td><a href='/viewInfo.jsp?key=<%= media.getKeyForTrans()  %>'>
			        	<%= media.getTitle() %>
			        	</a></td>
			        	<td><%=format.getSize()%></td>
			        	<td><a href='/serve?key=<%= format.getKeyForTrans()  %>'>
			        	Download
			        	</a></td>
			        	<td><a href='/stream.jsp?key=<%= format.getKeyForTrans()  %>'>
			        	Stream
			        	</a></td>
			        	<td><input type="checkbox" name="formatKey" value="<%= format.getKeyForTrans()  %>" /></td></tr>
			        	<% current++; %>
		       <% }} %>
			</table>
			<a href="/deleteAll">Delete all files</a> &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;
			 &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;
			  &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="Delete" /></form>
      </div>
    </div>
    <div id="footer">
      <p><a href="/">Home</a> | <a href="/">LOL Cats</a> | <a href="/">Contact Us</a></p>
      <p>Copyright &copy; IT CROWD | <a href="http://validator.w3.org/check?uri=referer">HTML5</a> | <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a> | <a href="http://www.html5webtemplates.co.uk">design dervived from HTML5webtemplates.co.uk</a></p>
    </div>
  </div>
  <%
  pm.close();
    } else { 
  %>
        <p>Hello!
		<a href="<%= userService.createLoginURL(request.getRequestURI()) %>">Sign in</a>
		to access media vault.</p>
  <% } %>
</body>
</html>
